package cn.aicnn.chatssespringboot.controller;

import cn.aicnn.chatssespringboot.dto.Account;
import cn.aicnn.chatssespringboot.dto.User;
import cn.aicnn.chatssespringboot.service.AccountService;
import cn.aicnn.chatssespringboot.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @PostMapping("/api/users/login")
    @ResponseBody
    public Map<String, Object> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        Map<String, Object> response = new HashMap<>();

        // 调用UserService中的登录方法
        User user = userService.login(username, password);

        if (user != null) {
            // 生成访问令牌等逻辑
            String access_token = generateAccessToken(user);

            response.put("code", "0");
            response.put("message", "SUCCESS");
            response.put("data", access_token);
        } else {
            response.put("code", "1");
            response.put("message", "ERROR");
        }

        return response;
    }

    // 模拟生成访问令牌的方法
    private String generateAccessToken(User user) {
        // 生成一个随机的访问令牌
        SecureRandom random = new SecureRandom();
        String accessToken = new BigInteger(130, random).toString(32);

        return accessToken;
    }

//    @PostMapping("/api/users/register")
//    public Map<String, String> register(@RequestBody User user) {
//        Map<String, String> response = new HashMap<>();
//
//        boolean success = userService.register(user);
//        if (success) {
//            response.put("code", "0");
//            response.put("message", "SUCCESS");
//            response.put("data", "注册成功");
//        } else {
//            response.put("code", "1");
//            response.put("message", "ERROR");
//            response.put("data", "用户名已存在或注册失败");
//        }
//
//        return response;
//    }

//    @GetMapping("/api/users/isExist")
//    public ResponseEntity<String> isExist(@RequestParam String username) {
//        boolean userExists = accountService.checkUserExists(username);
//        if (userExists) {
//            return ResponseEntity.ok("用户已存在");
//        } else {
//            return ResponseEntity.ok("用户不存在");
//        }
//    }



}